import Singleton from '../Base/Singleton'
import { ApiMsgEnum } from '../Common'
import { PlayerManager } from './PlayerManager'
import { Room } from './Room'

// 资源加载
export class RoomManager extends Singleton {
  static get Instance() {
    return super.GetInstance<RoomManager>()
  }
  // 自增房间号
  nextRoomID = 1

  // 房间集合
  rooms: Set<Room> = new Set()
  // id 映射 对应房间
  idMapRoom: Map<number, Room> = new Map()

  // 创建
  createRoom() {
    const room = new Room(this.nextRoomID++)
    this.rooms.add(room)
    this.idMapRoom.set(room.id, room)
    return room
  }

  // 销毁
  removeRoom(id: number) {
    const room = this.idMapRoom.get(id)
    if (room) {
      this.rooms.delete(room)
      this.idMapRoom.delete(room.id)
    }
  }
  // 关闭房间
  closeRoom(id: number) {
    const room = this.idMapRoom.get(id)
    if (room) {
      room.close()
      this.rooms.delete(room)
      this.idMapRoom.delete(room.id)
    }
  }
  // 获取单个-->执行过滤
  getRoomView({ id, players }: Room) {
    return { id, players: PlayerManager.Instance.getPlayersView(players) }
  }
  // 获取所有房间
  getRoomsView(rooms: Set<Room> = this.rooms) {
    return [...rooms].map(p => this.getRoomView(p))
  }
  // 同步所有房间列表
  syncRooms() {
    for (const player of PlayerManager.Instance.players) {
      player.connection.sendMsg(ApiMsgEnum.MsgRoomList, {
        list: this.getRoomsView(),
      })
    }
  }
  // 同步单个
  syncRoom(rid: number) {
    const room = this.idMapRoom.get(rid)
    if (room) {
      room.async()
    }
  }
}
